package com.ellfors.common.ext

import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.content.ContextCompat
import com.ellfors.common.app.MyApp

/**
 * ComposeView装载内容
 */
fun ComposeView.bindPage(page: @Composable () -> Unit) {
    this.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
    this.setContent { page() }
}

/**
 * 点击事件，无水波纹
 */
fun Modifier.clickNoShadow(onClick: () -> Unit) = composed {
    this.clickable(interactionSource = remember { MutableInteractionSource() },
        indication = null,
        onClick = { onClick() })
}

/**
 * 获取资源文件中的颜色并转换为Color
 */
@Composable
fun getResColor(resId: Int): Color {
    return try {
        Color(ContextCompat.getColor(MyApp.context, resId))
    } catch (e: UninitializedPropertyAccessException) {
        //这个是在预览时，Application实际还没初始化，所以需要用LocalContext
        val context = LocalContext.current
        Color(ContextCompat.getColor(context, resId))
    }
}